<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/22
 * Time: 09:25
 */

namespace wechat\controllers;

use tt\common\components\TtPagination;
use tt\common\help\ModelHelper;
use tt\common\help\RequestHelp;
use tt\common\help\ResponseHelp;
use ttcommon\aop\annotation\ControllerAnnotation;
use ttcommon\base\Arrays;
use ttcommon\base\Data;
use ttext\backend\admin\hook\QuickMenuHook;
use wechat\models\WeKeyword;
use wechat\services\WeConfigService;
use wechat\services\WeContentService;
use wechat\services\WeKeywordService;
use yii\base\UserException;

/**
 * @title [微信]关键词
 */
class KeywordController extends BaseWechatController implements ControllerAnnotation
{
    /**
     * @title 列表
     * @return string
     */
    public function actionIndex()
    {
        if ($api = $this->hasApi()) {
            if ('list' == $api) {
                $query = WeKeyword::find()->select(['id', 'wc_id', 'keyword', 'start', 'end', 'status', 'c_type', 'c_id']);
                $pagination = new TtPagination(['totalCount' => $query->count()]);
                $data = [];
                foreach ($query->offset($pagination->offset)->limit($pagination->limit)->asArray()->each() as $item) {
//                pr($item);
                    $item['wc_title'] = $item['wc_id'] ? WeConfigService::find($item['wc_id'], 'title') : '';
                    $item['status_text'] = WeKeyword::statusText($item['status']);
                    $item['c_type_text'] = $item['c_id'] ? WeKeyword::cTypeText($item['c_type']) : '';
                    $item['c_title'] = $item['c_id'] ? WeContentService::find($item['c_id'], 'title') : '';
                    $data[] = $item;
                }
                $result = [
                    'total' => $pagination->totalCount,
                    'result' => $data
                ];
                ResponseHelp::send($result);
            } elseif ('preview' == $api) {
                QuickMenuHook::$disabled = true;
                if (!$id = Data::hasInt($_GET, 'id')) {
                    throw new \Exception('参数错误');
                }
                $content = WeKeywordService::contentFromKeywordId($id);
                return $this->render('preview', [
                    'content' => $content
                ]);
            } else {
                throw new \Exception('不支持的接口参数');
            }
        }
        return $this->render('index');
    }

    private function findById($id)
    {
        if (!$model = WeKeyword::findOne(['id' => $id])) {
            throw new \Exception('找不到指定的数据');
        }
        return $model;
    }

    /**
     * @title 添加/编辑
     */
    public function actionEdit($id = 0)
    {
        QuickMenuHook::$disabled = true;
        $model = $id ? $this->findById($id) : new WeKeyword();
        if (RequestHelp::isPost()) {
            $data = RequestHelp::requestData();
            if ($postId = Data::hasInt($data, 'id')) {
                if ($postId != $id) {
                    throw new \Exception('参数错误');
                }
            }
            $keys = ['wc_id', 'keyword', 'start', 'end', 'status', 'c_type', 'c_id']; // 验证提交的数据
            Data::hasSet($data, $keys);
            // 如果要追加其它的键，请使用 array_merge($keys,[other])
            $model->attributes = Arrays::values($data, $keys);
            if ($model->validate() && $model->save()) {
                ResponseHelp::send($model->toArray());
            } else {
                throw new UserException(ModelHelper::errorMessages($model));
            }
        }
        if (!$id) {
            $model->status = WeKeyword::STATUS_ACTIVE;
        }
        return $this->render('edit', [
            'model' => $model
        ]);
    }

    /**
     * @title 删除
     */
    public function actionDelete($id)
    {
        if (RequestHelp::isPost()) {
            $model = $this->findById($id);
            if ($model->delete() === false) {
                throw new UserException('删除失败');
            }
            ResponseHelp::send('删除成功');
        } else {
            RequestHelp::throwRequestMethodError();
        }
    }

    /**
     * @title 快速选择
     * @param int $type
     */
    public function actionSelected($type)
    {
        if (!in_array($type, array_keys(WeKeyword::cTypeText()))) {
            throw new \Exception('不支持的回复类型');
        }
        $hasApi = $this->hasApi(); // 是否为 api 请求数据
        switch ($type) {
            case WeKeyword::C_TYPE_BLOG_ARTICLE:
                return $this->render('selected_blog');
                break;
            default:
                return $this->render('selected_content');
        }
    }
}